package com.asseco.mio.codex.controllers;

import com.asseco.mio.core.model.AuditLog;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

import com.asseco.mio.codex.MeasuresTaken;
import com.asseco.mio.core.webapp.controller.BaseFormController;
import org.appfuse.Constants;

@Controller
@RequestMapping("/measurestakenform*")
public class MeasuresTakenFormController extends BaseFormController {

    private GenericManager<MeasuresTaken, String> measuresTakenManager;
    private GenericManager<AuditLog, String> auditLoggerManager = null;
    @Autowired(required = false)
    Validator validator;

    @Autowired
    public void setMeasuresTakenManager(@Qualifier("measuresTakenManager") GenericManager<MeasuresTaken, String> measuresTakenManager) {
        this.measuresTakenManager = measuresTakenManager;
    }

    @Autowired
    public void setAuditLoggerManager(GenericManager<AuditLog, String> auditLoggerManager) {
        this.auditLoggerManager = auditLoggerManager;
    }

    public MeasuresTakenFormController() {
        setCancelView("redirect:measurestaken");
        setSuccessView("redirect:measurestaken");
    }

    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected MeasuresTaken showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
                String userString = request.getRemoteUser();
           try{     if (!request.isUserInRole(Constants.ADMIN_ROLE)) throw new Exception("");

           }catch (Exception e){

               response.sendRedirect("/MIO/mainMenu");
           }
        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "measurestakenform", "measurestaken.show", measuresTakenManager.get(id).getName(),
                    "", request.getRemoteHost(), new Date()));
            return measuresTakenManager.get(id);
        }


        return new MeasuresTaken();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(MeasuresTaken measureTaken, BindingResult errors, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }
        if (validator != null) { // validator is null during testing
            validator.validate(measureTaken, errors);

            if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
                return "measurestakenform";
            }
        }

        log.debug("entering 'onSubmit' method...");

        boolean isNew = (measureTaken.getId() == null);
        String success = getSuccessView();
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
             auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "measurestakenform", "measuresTaken.deleted", measureTaken.getName(),
                    "", request.getRemoteHost(), new Date()));
            measuresTakenManager.remove(measureTaken.getId());
            saveMessage(request, getText("measuresTaken.deleted", locale));
           

        } else {
            measuresTakenManager.save(measureTaken);
            String key = (isNew) ? "measuresTaken.added" : "measuresTaken.updated";
            saveMessage(request, getText(key, locale));
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "measurestakenform", key, measureTaken.getName(),
                    "", request.getRemoteHost(), new Date()));

            if (!isNew) {
                success = "redirect:measurestakenform?id=" + measureTaken.getId();
            }
        }

        return success;
    }

    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        super.initBinder(request, binder);
        SimpleDateFormat dateFormat =
                new SimpleDateFormat(getText("dd/MM/yyyy", request.getLocale()));
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
    }
}
